package com.dhl.fin.api.service;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.dhl.fin.api.common.dto.QueryDto;
import com.dhl.fin.api.common.service.CommonService;
import com.dhl.fin.api.common.util.CollectorUtil;
import com.dhl.fin.api.common.util.MapUtil;
import com.dhl.fin.api.common.util.ObjectUtil;
import com.dhl.fin.api.dao.MyDailyRateDao;
import com.dhl.fin.api.domain.DailyRate;
import com.dhl.fin.api.dto.BankStatementRequestDTO;
import com.dhl.fin.api.dto.LastMonthInterestStatementDTO;
import com.dhl.fin.api.enums.BusinessTypeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author CuiJianbo
 * @since 2025/3/16
 */
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class DailyRateService extends CommonService<DailyRate> {

    @Autowired
    private BankStatementService bankStatementService;

    @Autowired
    private MyDailyRateDao myDailyRateDao;

    private static final int STEP_LENGTH = 300;

    public void batchInsert(List<DailyRate> dailyRateList) {
        List<DailyRate> temp = new ArrayList<>();
        for (int i = 0; i < dailyRateList.size(); i++) {
            if (i > 0 && i % STEP_LENGTH == 0) {
                myDailyRateDao.batchInsert(temp);
                temp.clear();
            }
            temp.add(dailyRateList.get(i));
        }
        if (CollectorUtil.isNoTEmpty(temp)) {
            myDailyRateDao.batchInsert(dailyRateList);
        }
    }

    /**
     * 计算上月的活期账户总利息
     */
    public void calculateLastMonthInterest() throws Exception {
        DateTime date = DateUtil.offset(DateUtil.date(), DateField.MONTH, -1);
        int month = DateUtil.month(date) + 1;
        int year = DateUtil.year(date);
        List<Map> interestData = myDailyRateDao.selectSumInterest(month, year);
        for (Map p : interestData) {
            LastMonthInterestStatementDTO lastMonthInterestStatementDTO = new LastMonthInterestStatementDTO();
            lastMonthInterestStatementDTO.setBankAccountId(MapUtil.getLong(p, "bankAccountId"));
            lastMonthInterestStatementDTO.setTotalInterest(MapUtil.getDouble(p, "totalInterest"));
            lastMonthInterestStatementDTO.setMonth(month);
            lastMonthInterestStatementDTO.setYear(year);
            bankStatementService.addMonthlyInterestStatement(lastMonthInterestStatementDTO);
        }
    }

    public boolean checkDailyInterestIsDone(String date) throws Exception {
        DailyRate dailyRate = get(QueryDto.builder()
                .available()
                .addWhere("day = '" + date + "'")
                .build());

        return ObjectUtil.notNull(dailyRate);
    }

}
